<template>
    <div class="question-test-container">
      <div class="header">
        <h1>MBTI人格类型测试</h1>
        <p class="subtitle">完成所有题目以解锁您的人格类型分析</p>
      </div>

      <div class="test-progress">
        <div class="progress-bar">
          <div class="progress-fill" :style="{ width: progressPercentage + '%' }"></div>
        </div>
        <div class="progress-text">完成进度: {{ currentIndex + 1 }}/{{ questions.length }}</div>
      </div>

      <div v-if="loading" class="loading-container">
        <el-spinner size="large"></el-spinner>
        <p>加载测试题目中...</p>
      </div>

      <div v-else-if="error" class="error-container">
        <div class="error-card">
          <i class="el-icon-error-circle-outline error-icon"></i>
          <h3 class="error-title">加载失败</h3>
          <p class="error-message">{{ error.message }}</p>
          <el-button type="primary" @click="fetchQuestions">重试</el-button>
        </div>
      </div>

      <div v-else class="question-card-container">
        <transition name="fade" mode="out-in">
          <div v-if="currentQuestion" class="question-card" :key="currentIndex">
            <div class="question-header">
              <div class="question-number">题目 {{ currentIndex + 1 }}</div>
              <div class="question-category">人格倾向测试</div>
            </div>

            <div class="question-content">
              <h2 class="question-text">{{ currentQuestion.description }}</h2>

              <div class="options-container">
                <div
                  v-for="(option, index) in currentQuestion.options"
                  :key="index"
                  class="option"
                  :class="{ 'selected': selectedOption === index }"
                  @click="selectOption(index)"
                >
                  <div class="option-letter">{{ String.fromCharCode(65 + index) }}</div>
                  <div class="option-text">{{ option.text }}</div>
                </div>
              </div>
            </div>

            <div class="question-footer">
              <div class="navigation">
                <el-button
                  class="nav-btn prev-btn"
                  :disabled="currentIndex === 0"
                  @click="prevQuestion"
                >
                  <i class="el-icon-arrow-left"></i> 上一题
                </el-button>

                <el-button
                  class="nav-btn next-btn"
                  type="primary"
                  :disabled="!currentQuestion.answered"
                  @click="nextQuestion"
                >
                  下一题 <i class="el-icon-arrow-right"></i>
                </el-button>
              </div>
            </div>
          </div>
        </transition>
      </div>

      <div class="statistics">
        <div class="stat-card">
          <div class="stat-value">{{ answeredCount }}</div>
          <div class="stat-label">已答题数</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{ remainingCount }}</div>
          <div class="stat-label">剩余题数</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{ totalCount }}</div>
          <div class="stat-label">总题数</div>
        </div>
      </div>

      <div v-if="showResults" class="result-container">
        <div class="result-card">
          <div class="result-header">
            <h2>测试完成！</h2>
            <p>恭喜您完成了全部测试题目</p>
          </div>

          <div class="result-content">
            <div class="mbti-type">
              <div class="type-label">您的人格类型</div>
              <div class="type-value">{{ mbtiResult }}</div>
            </div>

            <div class="result-description">
              <h3>人格描述</h3>
              <p v-html="personalityDetail.description || '暂无描述信息'"></p>
            </div>

            <div class="detail-item">
              <span class="detail-label">领导模式:</span>
              <span v-html="personalityDetail.ladder || '暂无信息'"></span>
            </div>
            <div class="detail-item">
              <span class="detail-label">解决问题方式:</span>
              <span v-html="personalityDetail.solve || '暂无信息'"></span>
            </div>
            <div class="detail-item">
              <span class="detail-label">适合领域:</span>
              <span v-html="personalityDetail.are || '暂无信息'"></span>
            </div>
            <div class="detail-item">
              <span class="detail-label">适合职业:</span>
              <span v-html="personalityDetail.career || '暂无信息'"></span>
            </div>
            <div class="detail-item">
              <span class="detail-label">缺点:</span>
              <span v-html="personalityDetail.bad || '暂无信息'"></span>
            </div>
            <div class="detail-item">
              <span class="detail-label">建议:</span>
              <span v-html="personalityDetail.suggest || '暂无信息'"></span>
            </div>
          </div>

          <div class="result-footer">
            <el-button type="primary" @click="restartTest">重新测试</el-button>
            <el-button type="primary" @click="saveTestResult">保存测试结果</el-button>
          </div>
        </div>
      </div>

      <!-- 调试信息 -->

    </div>
  </template>

  <script>
  import { getQuestion, addTest } from '@/api/question' // 导入API
  import { getPersonalityDetail } from '@/api/role' // 导入API

  import { UserModule } from '@/store/modules/user'
  export default {
    name: 'QuestionTest',
    data() {
      return {
        sno: '',
        currentIndex: 0,
        selectedOption: null,
        showResults: false,
        questions: [], // 初始化为空数组，将从后端获取
        scores: { E: 0, I: 0, S: 0, N: 0, T: 0, F: 0, J: 0, P: 0 }, // 计分对象
        mbtiResult: '', // 计算结果
        loading: false,
        error: null,
        saveLoading: false, // 保存结果加载状态
        saveError: null, // 保存结果错误信息
        // 备用数据结构配置
        dataStructureConfig: {
          primaryPath: 'records',
          alternativePaths: ['questionList', 'items', 'dataList']
        },
        personalityDetail: {}, // 存储人格详细信息
        personalityLoading: false, // 加载人格信息的状态
        personalityError: null, // 加载人格信息的错误
        personalityLoaded: false // 新增：标记人格信息是否加载完成
      }
    },
    computed: {
      // 进度百分比计算属性
      progressPercentage() {
        if (this.questions.length === 0) return 0;
        return Math.round((this.currentIndex + 1) / this.questions.length * 100);
      },

      // 当前问题计算属性
      currentQuestion() {
        if (!this.questions.length) return null;
        return this.currentIndex < this.questions.length
          ? this.questions[this.currentIndex]
          : null;
      },

      // 已答题数
      answeredCount() {
        return this.questions.filter(q => q.answered).length;
      },

      // 剩余题数
      remainingCount() {
        return this.questions.length - this.answeredCount;
      },

      // 总题数
      totalCount() {
        return this.questions.length;
      }
    },
    created() {
      this.sno = UserModule.username;
      this.fetchQuestions();
    },
    methods: {
      // 获取题目数据
      async fetchQuestions() {
        this.loading = true;
        this.error = null;
        try {
          const res = await getQuestion({ page: 1, pageSize: 54 }); // 获取所有题目

          console.log('API响应数据:', res); // 调试用日志

          // 优化数据格式检查逻辑
          if (
            res &&
            res.data &&
            typeof res.data === 'object'
          ) {
            // 尝试从主路径获取题目
            let questionsFound = false;

            // 尝试主路径
            if (Array.isArray(res.data[this.dataStructureConfig.primaryPath])) {
              this.questions = this.processQuestions(res.data[this.dataStructureConfig.primaryPath]);
              questionsFound = this.questions.length > 0;
              console.log(`从主路径 ${this.dataStructureConfig.primaryPath} 获取到 ${this.questions.length} 个题目`);
            }

            // 如果主路径没有获取到题目，尝试备用路径
            if (!questionsFound && this.dataStructureConfig.alternativePaths) {
              for (const path of this.dataStructureConfig.alternativePaths) {
                if (Array.isArray(res.data[path])) {
                  this.questions = this.processQuestions(res.data[path]);
                  questionsFound = this.questions.length > 0;
                  console.log(`从备用路径 ${path} 获取到 ${this.questions.length} 个题目`);
                  if (questionsFound) break;
                }
              }
            }

            // 如果还是没有找到题目，检查是否有单个题目对象
            if (!questionsFound && res.data.id && res.data.description) {
              this.questions = [this.processQuestion(res.data)];
              questionsFound = true;
              console.log('从单个题目对象获取到1个题目');
            }

            // 如果仍然没有找到题目，尝试更深入的路径
            if (!questionsFound && res.data.data && typeof res.data.data === 'object') {
              for (const key in res.data.data) {
                if (Array.isArray(res.data.data[key])) {
                  this.questions = this.processQuestions(res.data.data[key]);
                  questionsFound = this.questions.length > 0;
                  console.log(`从深层路径 data.${key} 获取到 ${this.questions.length} 个题目`);
                  if (questionsFound) break;
                }
              }
            }

            // 检查是否成功获取到题目
            if (!questionsFound) {
              throw new Error('API返回的数据中没有包含有效题目结构');
            }
          } else {
            // 更详细的错误提示，便于调试
            let errorMsg = 'API返回的数据格式不正确';
            if (!res) errorMsg = '未接收到API响应';
            else if (!res.data) errorMsg = 'API响应中缺少data字段';
            else if (typeof res.data !== 'object') errorMsg = 'data字段不是对象';
            throw new Error(errorMsg);
          }
        } catch (error) {
          console.error('获取题目失败:', error);
          this.error = error;
          // 显示友好的错误提示
          this.$message.error('获取测试题目失败: ' + (error.message || '请检查网络连接后重试'));
        } finally {
          this.loading = false;
        }
      },

      // 处理题目数据的辅助方法
      processQuestions(items) {
        return items.map(item => this.processQuestion(item));
      },

      // 处理单个题目的辅助方法
      processQuestion(item) {
        // 检查选项结构是否符合预期
        let options = [];

        // 处理标准选项结构
        if (item.optiona && item.optionb) {
          options = [
            { text: item.optiona || '选项A', value: item.ansera || '' },
            { text: item.optionb || '选项B', value: item.anserb || '' }
          ];
        }
        // 处理选项数组结构
        else if (Array.isArray(item.options) && item.options.length >= 2) {
          options = item.options.slice(0, 2).map((opt, idx) => ({
            text: opt.text || `选项${String.fromCharCode(65 + idx)}`,
            value: opt.value || ''
          }));
        }
        // 默认选项
        else {
          options = [
            { text: '选项A', value: '' },
            { text: '选项B', value: '' }
          ];
        }

        return {
          id: item.id || 0,
          description: item.description || '题目描述缺失',
          answered: false,
          options: options,
          selectedOption: null // 保存用户选择的选项索引
        };
      },

      selectOption(index) {
        if (!this.currentQuestion) return;

        const question = this.currentQuestion;
        const selectedValue = question.options[index].value;

        // 更新分数
        if (selectedValue && this.scores.hasOwnProperty(selectedValue)) {
          this.scores[selectedValue]++;
        }

        // 更新题目状态
        question.answered = true;
        question.selectedOption = index; // 保存用户选择的选项索引
        this.selectedOption = index;
      },

      prevQuestion() {
        if (this.currentIndex > 0) {
          this.currentIndex--;
          this.selectedOption = this.questions[this.currentIndex].answered
            ? this.questions[this.currentIndex].selectedOption
            : null;
        }
      },

      nextQuestion() {
        if (this.currentIndex < this.questions.length - 1) {
          this.currentIndex++;
          this.selectedOption = this.questions[this.currentIndex].answered
            ? this.questions[this.currentIndex].selectedOption
            : null;
        } else {
          this.calculateResult();
          this.getPersonalityDetail();
          this.showResults = true;
        }
      },

      // 计算MBTI结果
      calculateResult() {
        // 根据规则计算每个维度
        const ei = this.scores.E >= this.scores.I ? 'E' : 'I';
        const sn = this.scores.S >= this.scores.N ? 'S' : 'N';
        const tf = this.scores.T >= this.scores.F ? 'T' : 'F';
        const jp = this.scores.J >= this.scores.P ? 'J' : 'P';

        // 应用同分处理规则
        this.mbtiResult = [
          this.scores.E === this.scores.I ? 'I' : ei,
          this.scores.S === this.scores.N ? 'N' : sn,
          this.scores.T === this.scores.F ? 'F' : tf,
          this.scores.J === this.scores.P ? 'P' : jp
        ].join('');
      },

      // 获取人格详细信息
      async getPersonalityDetail() {
        this.personalityLoading = true;
        this.personalityError = null;
        this.personalityLoaded = false;

        try {
          if (!this.mbtiResult) {
            throw new Error('MBTI类型结果为空');
          }

          const res = await getPersonalityDetail(this.mbtiResult);

          console.log('原始API响应:', res); // 输出完整原始响应

          if (res && res.data) {
            // 检查数据是否嵌套在更深层级
            let personalityData = res.data;
            if (personalityData.data && typeof personalityData.data === 'object') {
              console.log('检测到深层嵌套数据结构，使用res.data.data');
              personalityData = personalityData.data;
            }

            // 处理数据中的换行符
            const processedData = { ...personalityData };
            for (const key in processedData) {
              if (typeof processedData[key] === 'string') {
                processedData[key] = processedData[key].replace(/\r\n/g, '<br>').replace(/\n/g, '<br>');
              }
            }

            // 验证数据字段完整性
            this.validatePersonalityData(processedData);

            console.log('处理后的人格数据:', processedData);

            this.personalityDetail = processedData;
            this.personalityLoaded = true;
          } else {
            throw new Error('获取人格详细信息失败');
          }
        } catch (error) {
          console.error('获取人格详细信息失败:', error);
          this.personalityError = error;
          this.$message.error('获取人格详细信息失败: ' + (error.message || '请稍后再试'));
        } finally {
          this.personalityLoading = false;
        }
      },

      // 验证人格数据字段完整性
      validatePersonalityData(data) {
        const requiredFields = ['description', 'ladder', 'solve', 'are', 'career', 'bad', 'suggest'];
        let hasMissingFields = false;

        requiredFields.forEach(field => {
          if (!data[field]) {
            console.warn(`人格数据缺少字段: ${field}`);
            hasMissingFields = true;
          }
        });

        if (hasMissingFields) {
          console.log('完整人格数据:', data);
        }
      },

      // 重启测试
      restartTest() {
        this.currentIndex = 0;
        this.selectedOption = null;
        this.showResults = false;
        this.scores = { E: 0, I: 0, S: 0, N: 0, T: 0, F: 0, J: 0, P: 0 };
        this.personalityDetail = {};
        this.personalityLoaded = false;

        this.questions.forEach(q => {
          q.answered = false;
          q.selectedOption = null;
        });
      },

      // 保存测试结果
      async saveTestResult() {
        if (!this.mbtiResult) {
          this.$message.error('请先完成测试');
          return;
        }

        this.saveLoading = true;
        this.saveError = null;

        try {
          // 整理测试结果数据，匹配后端TestDTO结构
          const testData = {
            sno: this.sno,
            mbti: this.mbtiResult
          };

          // 调用后端保存接口
          const response = await addTest(testData);

          if (response ) {
            this.$message.success('测试结果保存成功');
          } else {
            throw new Error(response && response.message || '保存失败，请稍后再试');
          }
        } catch (error) {
          this.saveError = error;
          this.$message.error('保存测试结果失败: ' + (error.message || '请检查网络连接后重试'));
        } finally {
          this.saveLoading = false;
        }
      }
    }
  }
  </script>

  <style scoped>
  /* 保持原有样式不变 */
  .question-test-container {
    max-width: 800px;
    margin: 0 auto;
    padding: 30px 20px;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  }

  .header {
    text-align: center;
    margin-bottom: 30px;
  }

  .header h1 {
    font-size: 2.2rem;
    color: #2c3e50;
    margin-bottom: 10px;
    font-weight: 700;
  }

  .subtitle {
    font-size: 1.1rem;
    color: #7f8c8d;
  }

  .test-progress {
    margin-bottom: 30px;
  }

  .progress-bar {
    height: 12px;
    background: #e0e7ff;
    border-radius: 6px;
    overflow: hidden;
    margin-bottom: 10px;
    box-shadow: inset 0 1px 3px rgba(0,0,0,0.1);
  }

  .progress-fill {
    height: 100%;
    background: linear-gradient(90deg, #6a11cb 0%, #2575fc 100%);
    border-radius: 6px;
    transition: width 0.5s ease;
  }

  .progress-text {
    text-align: right;
    font-size: 0.95rem;
    color: #5d6d7e;
  }

  .question-card-container {
    perspective: 1000px;
    margin-bottom: 40px;
  }

  .question-card {
    background: white;
    border-radius: 15px;
    padding: 30px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
    transform-style: preserve-3d;
  }

  .question-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 25px;
    padding-bottom: 15px;
    border-bottom: 1px solid #f0f2f5;
  }

  .question-number {
    font-size: 1.2rem;
    font-weight: 600;
    color: #3498db;
  }

  .question-category {
    font-size: 0.9rem;
    background: #f0f7ff;
    color: #3498db;
    padding: 5px 12px;
    border-radius: 20px;
  }

  .question-content {
    margin-bottom: 25px;
  }

  .question-text {
    font-size: 1.3rem;
    line-height: 1.6;
    color: #2c3e50;
    margin-bottom: 30px;
  }

  .options-container {
    display: grid;
    gap: 15px;
  }

  .option {
    display: flex;
    align-items: center;
    padding: 18px 20px;
    border-radius: 12px;
    background: #f8f9fa;
    border: 2px solid #e9ecef;
    cursor: pointer;
    transition: all 0.3s ease;
  }

  .option:hover {
    border-color: #a5d8ff;
    background: #edf7ff;
    transform: translateY(-3px);
  }

  .option.selected {
    border-color: #4dabf7;
    background: #e7f5ff;
    box-shadow: 0 5px 15px rgba(77, 171, 247, 0.2);
  }

  .option-letter {
    width: 36px;
    height: 36px;
    min-width: 36px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    background: #e9ecef;
    color: #495057;
    font-weight: 600;
    margin-right: 15px;
    font-size: 1rem;
  }

  .option.selected .option-letter {
    background: #4dabf7;
    color: white;
  }

  .option-text {
    font-size: 1.05rem;
    color: #495057;
    line-height: 1.5;
  }

  .question-footer {
    display: flex;
    justify-content: center;
    align-items: center;
    padding-top: 20px;
    border-top: 1px solid #f0f2f5;
  }

  .navigation {
    display: flex;
    gap: 15px;
    width: 100%;
    justify-content: center;
  }

  .nav-btn {
    padding: 10px 25px;
    border-radius: 8px;
    font-weight: 500;
    transition: all 0.3s ease;
  }

  .prev-btn {
    background: #f8f9fa;
    color: #495057;
    border: 1px solid #e9ecef;
  }

  .prev-btn:hover:not(:disabled) {
    background: #e9ecef;
    transform: translateY(-2px);
  }

  .next-btn {
    background: linear-gradient(90deg, #4facfe 0%, #00f2fe 100%);
    color: white;
    border: none;
    box-shadow: 0 4px 15px rgba(79, 172, 254, 0.4);
  }

  .next-btn:hover:not(:disabled) {
    box-shadow: 0 6px 20px rgba(79, 172, 254, 0.6);
    transform: translateY(-2px);
  }

  /* 统计卡片 */
  .statistics {
    display: flex;
    justify-content: center;
    gap: 30px;
    margin-bottom: 40px;
  }

  .stat-card {
    background: white;
    border-radius: 12px;
    padding: 25px 30px;
    text-align: center;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
    transition: transform 0.3s ease;
    min-width: 150px;
    background: linear-gradient(135deg, #f0f7ff 0%, #e4edf5 100%);
  }

  .stat-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
  }

  .stat-value {
    font-size: 2.2rem;
    font-weight: 700;
    color: #3498db;
    margin-bottom: 8px;
  }

  .stat-label {
    font-size: 1rem;
    color: #5d6d7e;
    font-weight: 500;
  }

  /* 结果容器 */
  .result-container {
    background: white;
    border-radius: 15px;
    padding: 30px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
    margin-top: 20px;
    animation: fadeIn 0.6s ease;
  }

  .result-card {
    text-align: center;
  }

  .result-header h2 {
    font-size: 1.8rem;
    color: #2c3e50;
    margin-bottom: 10px;
  }

  .result-header p {
    color: #7f8c8d;
    margin-bottom: 30px;
  }

  .mbti-type {
    margin: 25px 0;
    padding: 20px;
    background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
    border-radius: 12px;
    display: inline-block;
    min-width: 250px;
  }

  .type-label {
    color: rgba(255, 255, 255, 0.85);
    font-size: 1.1rem;
    margin-bottom: 5px;
  }

  .type-value {
    color: white;
    font-size: 3rem;
    font-weight: 800;
    letter-spacing: 3px;
  }

  .result-description {
    text-align: left;
    margin: 30px 0;
    padding: 20px;
    background: #f9fbfd;
    border-radius: 12px;
    border-left: 4px solid #3498db;
  }

  .result-description h3 {
    color: #3498db;
    margin-bottom: 15px;
    font-size: 1.3rem;
  }

  .result-description p {
    color: #555;
    line-height: 1.7;
  }

  .detail-item {
    text-align: left;
    margin-bottom: 15px;
    padding: 0 20px;
    font-size: 1rem;
  }

  .detail-label {
    font-weight: 600;
    color: #2c3e50;
    display: inline-block;
    min-width: 110px;
  }

  .result-footer {
    margin-top: 30px;
    display: flex;
    justify-content: center;
    gap: 15px;
  }

  /* 动画效果 */
  .fade-enter-active, .fade-leave-active {
    transition: opacity 0.3s, transform 0.4s;
  }
  .fade-enter, .fade-leave-to {
    opacity: 0;
    transform: translateX(30px);
  }

  @keyframes fadeIn {
    from {
      opacity: 0;
      transform: translateY(20px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .question-card {
      padding: 20px;
    }

    .question-text {
      font-size: 1.15rem;
    }

    .statistics {
      flex-direction: column;
      align-items: center;
      gap: 20px;
    }

    .stat-card {
      width: 80%;
    }

    .question-footer {
      flex-direction: column;
      gap: 15px;
    }

    .navigation {
      width: 100%;
      justify-content: space-between;
    }
  }

  @media (max-width: 480px) {
    .header h1 {
      font-size: 1.8rem;
    }

    .option {
      padding: 15px;
    }

    .option-text {
      font-size: 0.95rem;
    }

    .result-footer {
      flex-direction: column;
      align-items: center;
    }

    .result-footer .el-button {
      width: 100%;
      margin: 5px 0;
    }

    .navigation {
      flex-direction: column;
      align-items: center;
    }

    .nav-btn {
      width: 100%;
    }
  }

  /* 新增加载状态样式 */
  .loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 50px 0;
  }

  .loading-container p {
    margin-top: 20px;
    color: #7f8c8d;
    font-size: 1.1rem;
  }

  /* 新增错误状态样式 */
  .error-container {
    display: flex;
    justify-content: center;
    margin-top: 30px;
  }

  .error-card {
    text-align: center;
    padding: 40px;
    background: white;
    border-radius: 15px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
    max-width: 500px;
  }

  .error-icon {
    font-size: 48px;
    color: #f56c6c;
    margin-bottom: 20px;
  }

  .error-title {
    font-size: 1.5rem;
    color: #303133;
    margin-bottom: 15px;
  }

  .error-message {
    font-size: 1.1rem;
    color: #606266;
    margin-bottom: 30px;
  }

  /* 保存结果按钮加载状态样式 */
  .saving-loading {
    display: inline-block;
    margin-right: 8px;
    vertical-align: middle;
  }

  /* 调试区域样式 */
  .debug-container {
    margin-top: 20px;
    padding: 15px;
    background: #f5f5f5;
    border-radius: 8px;
    border: 1px solid #e0e0e0;
  }

  .debug-container h3 {
    margin-top: 0;
    color: #333;
    font-size: 1.2rem;
  }

  .debug-container pre {
    max-height: 300px;
    overflow: auto;
    background: #2d2d2d;
    color: #fff;
    padding: 15px;
    border-radius: 6px;
    font-size: 0.9rem;
  }
  </style>
